
import Foundation

protocol DappCallback {
    func onSuccess(data:[String:Any]) -> Void
    func onFailure(data:String) -> Void
}

actor DappSdk {
    static func dappHash(data:Data) -> String {
        return EcUtils.osnHash(data: data)
    }
    static func dappSign(key:String, data:Data) -> String? {
        return EcUtils.osnSign(priKey: key, data: data)
    }
    static func dappVerify(osnID:String, hash:Data, sign:String) -> Bool {
        return EcUtils.osnVerify(osnID: osnID, data: hash, sign: sign)
    }
    static func dappLogin(osnID:String, osnKey:String, target:String, url:String, callback:@escaping ([String:Any]?, String?)->Void) async {
        let log = Lander(url: url, osnID: osnID, osnKey: osnKey, target: target, callback: callback)
        _ = await log.dappLogin()
    }
    static func bip39Login(osnID:String, osnKey:String, target:String, url:String, username:String, callback:@escaping ([String:Any]?, String?)->Void) async {
        let log = Lander(url: url, osnID: osnID, osnKey: osnKey, target: target, callback: callback)
        log.username = username
        _ = await log.dappLogin()
    }
    static func doPost(_ urls: String, _ body: String, _ head:[String:Any]?) async -> String? {
        guard let url = URL(string: urls) else {
            //print("Invalid URL \(urls)")
            return nil
        }
        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        if let head = head {
            for (k,v) in head {
                request.setValue(v as? String, forHTTPHeaderField: k)
            }
        }else{
            request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        }
        do {
            let (data, response) = try await URLSession.shared.upload(for: request, from: body.data(using: .utf8)!)
            guard let httpResponse = response as? HTTPURLResponse, (200...299).contains(httpResponse.statusCode) else {
                //print("Request failed: \(response)")
                return nil
            }
            return String(data: data, encoding: .utf8)
        } catch {
            //print("http request error: \(error)")
        }
        return nil
    }
    static func setReply(error:String?, json:[String:Any]?) -> [String:Any] {
        var reply = json
        if reply == nil {
            reply = [:]
        }
        reply!["errCode"] = error == nil ? "0:success" : error
        //print("reply: \(reply!)")
        return reply!;
    }
    static func isSuccess(_ data:[String:Any]) -> Bool {
        if !data.keys.contains("errCode") {
            return false
        }
        let errCode = data["errCode"] as? String ?? ""
        return errCode == "success" || errCode == "0:success"
    }
    static func errCode(_ data:[String:Any]) -> String {
        if (!data.keys.contains("errCode")){
            return "none";
        }
        return data["errCode"] as? String ?? ""
    }
}
